package ps.client.gui.userlist;

import java.util.Vector;

import javax.swing.DefaultListModel;

import ps.server.net.ClientInfo;


@SuppressWarnings("serial")
public class UserListModel extends DefaultListModel {
    
    Vector<UserListEntry> entryList = new Vector<UserListEntry>();
    
    @Override
    public Object getElementAt(int index) {
        UserListEntry ret = null;
        try {
            ret = entryList.get(index);
        } catch (Exception ex) {
        }
        return ret;
    }
    
    public void setListData(String[] userNames) {
        entryList.clear();
        for (String userName : userNames) {
            UserListEntry entry = new UserListEntry();
            entry.userName = userName;
            entryList.add(entry);
        }
        
        int endIndex = entryList.size() > 0 ? entryList.size() - 1 : 0;
        fireContentsChanged(this, 0, endIndex);
        
        fireListDataChanged();
    }
    
    public void setListInfoData(ClientInfo[] clientInfos) {
        if (entryList.size() == clientInfos.length && clientInfos.length > 0) {
            for (int i = 0; i < clientInfos.length; i++) {
                UserListEntry entry = entryList.get(i);
                entry.ping = clientInfos[i].getPing();
                entry.afk = clientInfos[i].isAfk();
                entry.admin = clientInfos[i].getUser().isAdmin();
                entry.logReadAvtive = clientInfos[i].isLogReadActive();
                entry.linkDead = clientInfos[i].isLinkDead();
                entry.groupNumber = clientInfos[i].getGroupNumber();
            }
            fireContentsChanged(this, 0, entryList.size() - 1);
        }
    }
    
    @Override
    public void clear() {
        entryList.clear();
        fireContentsChanged(this, 0, 0);
        fireListDataChanged();
    }
    
    @Override
    public int getSize() {
        return entryList.size();
    }
    
    public int getGroupOfUser(String userName) {
        int ret = 0;
        
        synchronized (entryList) {
            for (UserListEntry user: entryList) {
                if (user.userName.equals(userName)) {
                    ret = user.groupNumber;
                    break;
                }
            }
        }
            
        return ret;
    }
    
    protected void fireListDataChanged() {
    }

}
